from django import forms

from django.core.exceptions import ValidationError

from web import models
from web.forms.bootstrap import BootStrapForm


class FolderModleForm(BootStrapForm,forms.ModelForm):
    def __init__(self,request,parent_object ,*args,**kwargs):
        super().__init__(*args,**kwargs)
        self.request=request
        self.parent_object = parent_object


    class Meta:
        model = models.FileRepository
        # fields = '__all__'
        fields = ['name']

    def clean_name(self):

        name = self.cleaned_data['name']

        #判断提交的文件夹名字 在当前目录 ！！！是否i经存在
        query_set = models.FileRepository.objects.filter( file_type=2, name=name, project=self.request.tracer.project)
        if self.parent_object:
            exists = query_set.filter(parent=self.parent_object).exists()


        else:

            exists = query_set.filter(parent__isnull=True).exists()

        if exists:
            raise  ValidationError('文件已经存在')

        return name


class FileModelForm(forms.ModelForm):
    etag = forms.CharField(label='ETag')

    class Meta:
        model = models.FileRepository
        exclude = ['project', 'file_type', 'update_user', 'update_datetime']

    def __init__(self, request, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.request = request

    def clean_file_path(self):
        return "https://{}".format(self.cleaned_data['file_path'])